package com.tfswx.ruleengine.database.handler.base;

import com.tfswx.ruleengine.compute.util.EnumUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.*;

/**
 * @author Ricky
 * @date 2021/2/25
 */
@Slf4j
public class BaseEnumTypeHandler<E extends Enum<E>> implements TypeHandler<E> {

    private Class<E> type;

    public BaseEnumTypeHandler() {
    }

    public BaseEnumTypeHandler(Class<E> type) {
        this.type = type;
    }

    @Override
    public void setParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        Integer code = EnumUtil.getCode(parameter);
        if (code != null) {
            ps.setInt(i, code);
        } else {
            ps.setNull(i, Types.INTEGER);
        }
    }

    @Override
    public E getResult(ResultSet rs, String columnName) throws SQLException {
        Object object = rs.getObject(columnName);
        if (object == null) {
            return null;
        }
        return EnumUtil.codeOf(rs.getInt(columnName), type);
    }

    @Override
    public E getResult(ResultSet rs, int columnIndex) throws SQLException {
        Object object = rs.getObject(columnIndex);
        if (object == null) {
            return null;
        }
        return EnumUtil.codeOf(rs.getInt(columnIndex), type);
    }

    @Override
    public E getResult(CallableStatement cs, int columnIndex) throws SQLException {
        Object object = cs.getObject(columnIndex);
        if (object == null) {
            return null;
        }
        return EnumUtil.codeOf(cs.getInt(columnIndex), type);
    }
}
